'use strict';

const db = uniCloud.database();
const dbCmd = db.command;

exports.main = async (event, context) => {
  const { taskId, receiverId, status } = event;
  
  if (!taskId || !receiverId) {
    return {
      code: 400,
      msg: '缺少必要参数'
    };
  }

  try {
    console.log('【updateTaskIncome】开始处理收入结算:', { taskId, receiverId, status });
    
    // 简化查找逻辑：直接通过 task_id 查找
    const incomeRes = await db.collection('task_income_records')
      .where({ task_id: taskId })
      .get();
    
    console.log('【updateTaskIncome】查询结果:', {
      taskId,
      foundRecords: incomeRes.data.length,
      records: incomeRes.data
    });
    
    if (incomeRes.data.length === 0) {
      console.log('【updateTaskIncome】未找到对应的收入记录');
      
      return {
        code: 404,
        msg: '未找到对应的收入记录',
        debug: {
          searchedTaskId: taskId,
          receiverId: receiverId
        }
      };
    }

    const incomeRecord = incomeRes.data[0];
    
    // 更新收入记录状态
    const updateData = {
      status: status
    };
    
    // 如果状态是processing，更新receiver_id
    if (status === 'processing') {
      updateData.receiver_id = receiverId;
    }
    
    // 如果状态是completed，记录完成时间
    if (status === 'completed') {
      updateData.complete_time = Date.now();
    }

    await db.collection('task_income_records')
      .doc(incomeRecord._id)
      .update(updateData);

    // 如果任务完成，将收入转入接单者钱包
    if (status === 'completed') {
      console.log('【updateTaskIncome】开始结算收入:', {
        receiverId,
        rewardAmount: incomeRecord.reward_amount
      });
      
      const balanceUpdateResult = await db.collection('uni-id-users')
        .doc(receiverId)
        .update({
          balance: dbCmd.inc(incomeRecord.reward_amount)
        });
      
      console.log('【updateTaskIncome】余额更新结果:', balanceUpdateResult);

      // 记录收入到账
      await db.collection('payment_records').add({
        payment_id: `INCOME_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
        user_id: receiverId,
        amount: incomeRecord.reward_amount,
        payment_method: 'system',
        type: 'task_income',
        status: 'success',
        task_info: { task_id: taskId },
        create_time: Date.now(),
        desc: '任务完成收入'
      });
    }

    return {
      code: 200,
      msg: '收入记录更新成功',
      data: {
        taskId,
        receiverId,
        status,
        rewardAmount: incomeRecord.reward_amount
      }
    };

  } catch (error) {
    console.error('更新任务收入失败:', error);
    return {
      code: 500,
      msg: '更新收入记录失败',
      error: error.message
    };
  }
};